package com.iot.manager;

import android.content.Intent;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.PopupMenu;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.widget.Toolbar;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentManager;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.google.android.material.bottomnavigation.BottomNavigationView;
import com.google.android.material.floatingactionbutton.FloatingActionButton;
import com.iot.manager.network.ApiService;
import com.iot.manager.network.RetrofitClient;
import com.iot.manager.data.models.Device;
import com.iot.manager.data.models.DeviceListResponse;
import com.iot.manager.ui.activities.DeviceProvisioningActivity;
import com.iot.manager.ui.fragments.DashboardFragment;
import com.iot.manager.ui.fragments.DevicesFragment;
import com.iot.manager.ui.fragments.SettingsFragment;
import com.iot.manager.utils.SharedPreferencesManager;
import com.iot.manager.network.WebSocketManager;
import com.iot.manager.ui.activities.LoginActivity;
import com.iot.manager.ui.activities.AddDeviceActivity;
import androidx.navigation.NavController;
import androidx.navigation.Navigation;
import androidx.navigation.ui.AppBarConfiguration;
import androidx.navigation.ui.NavigationUI;
import androidx.navigation.fragment.NavHostFragment;
import com.google.android.material.dialog.MaterialAlertDialogBuilder;

import java.util.ArrayList;
import java.util.List;

import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

public class MainActivity extends AppCompatActivity {
    private NavController navController;
    private AppBarConfiguration appBarConfiguration;
    private FloatingActionButton fabAddDevice;
    private ApiService apiService;
    private List<Device> deviceList;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        // 检查登录状态
        if (!SharedPreferencesManager.getInstance(this).isLoggedIn()) {
            startActivity(new Intent(this, LoginActivity.class));
            finish();
            return;
        }

        // 设置工具栏
        setSupportActionBar(findViewById(R.id.toolbar));

        // 设置底部导航
        BottomNavigationView bottomNavigationView = findViewById(R.id.bottom_navigation);
        NavHostFragment navHostFragment = (NavHostFragment) getSupportFragmentManager()
                .findFragmentById(R.id.nav_host_fragment);
        if (navHostFragment != null) {
            navController = navHostFragment.getNavController();
            appBarConfiguration = new AppBarConfiguration.Builder(
                    R.id.navigation_dashboard,
                    R.id.navigation_devices,
                    R.id.navigation_settings
            ).build();

            NavigationUI.setupActionBarWithNavController(this, navController, appBarConfiguration);
            NavigationUI.setupWithNavController(bottomNavigationView, navController);
        }

        apiService = RetrofitClient.getInstance().getApiService();
        deviceList = new ArrayList<>();

        fabAddDevice = findViewById(R.id.fab_add_device);

        // 设置 token
        String token = SharedPreferencesManager.getInstance(this).getToken();
        if (token != null) {
            RetrofitClient.getInstance().setToken(token);
        }

        // 初始化 WebSocket
        initWebSocket();

        // 设置悬浮按钮点击事件
        fabAddDevice.setOnClickListener(v -> showAddDeviceOptions());
    }

    @Override
    protected void onResume() {
        super.onResume();
        loadDevices();
    }

    private void loadDevices() {
        apiService.getDevices().enqueue(new Callback<List<Device>>() {
            @Override
            public void onResponse(Call<List<Device>> call, Response<List<Device>> response) {
                if (response.isSuccessful() && response.body() != null) {
                    deviceList.clear();
                    deviceList.addAll(response.body());
                }
            }

            @Override
            public void onFailure(Call<List<Device>> call, Throwable t) {
                // 处理错误
            }
        });
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.menu_main, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        int id = item.getItemId();
        if (id == android.R.id.home) {
            finish();
            return true;
        } else if (id == R.id.action_logout) {
            logout();
            return true;
        }
        return super.onOptionsItemSelected(item);
    }

    private void logout() {
        new MaterialAlertDialogBuilder(this)
                .setTitle(R.string.logout)
                .setMessage(R.string.logout_confirmation)
                .setPositiveButton(R.string.confirm, (dialog, which) -> {
                    SharedPreferencesManager.getInstance(this).clearLoginInfo();
                    Intent intent = new Intent(this, LoginActivity.class);
                    startActivity(intent);
                    finish();
                })
                .setNegativeButton(R.string.cancel, null)
                .show();
    }

    @Override
    public boolean onSupportNavigateUp() {
        return NavigationUI.navigateUp(navController, appBarConfiguration)
                || super.onSupportNavigateUp();
    }

    @Override
    public void onBackPressed() {
        super.onBackPressed();
        WebSocketManager.getInstance(this).disconnect();
    }

    private void showAddDeviceOptions() {
        PopupMenu popup = new PopupMenu(this, fabAddDevice);
        popup.getMenuInflater().inflate(R.menu.menu_add_device, popup.getMenu());

        popup.setOnMenuItemClickListener(item -> {
            int itemId = item.getItemId();
            if (itemId == R.id.action_create_device) {
                Intent intent = new Intent(MainActivity.this, AddDeviceActivity.class);
                startActivity(intent);
                return true;
            } else if (itemId == R.id.action_network_config) {
                Intent intent = new Intent(MainActivity.this, DeviceProvisioningActivity.class);
                startActivity(intent);
                return true;
            }
            return false;
        });

        popup.show();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        WebSocketManager.getInstance(this).disconnect();
    }

    private void initWebSocket() {
        String token = SharedPreferencesManager.getInstance(this).getToken();
        if (token == null) {
            return;
        }
        WebSocketManager.getInstance(this).connect(token);
    }
} 